//
//  ClubDraftViewController.swift
//  77Club
//
//  Created by Apple on 2024/12/25.
//

import UIKit
import Photos

class ClubDraftViewController: ClubBaseViewController, RaeAnimationProtocol {

    private let navView = c_make_ex(UIView.self)
        .bgColor(.white).end()
    private let backButton = c_make_ex(UIButton.self)
        .image("Common_blackBack").end()
    private let titleLabel = c_make_ex(UILabel.self)
        .text("本地草稿").color(.black).font(16.font_semiBold).end()
    private let exploreLabel = c_make_ex(UILabel.self)
        .text("草稿在应用卸载后会被删除，请及时发布")
        .color("#969799").font(12.font_regular).end()
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(ClubForumDraftCell.self)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
//        tableView.rowHeight = 130.0.Scale
        return tableView
    }()
    var communityId: String = ""
    private var empteView = ClubEmptyView()
    private var dataSource = [[String: Any]]()
    
    var updateDataBlock: (() -> Void)?
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
            self.loadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.subviews{
            navView
            backButton
            titleLabel
            exploreLabel
            tableView
            empteView
        }
        
        navView.leading(0).trailing(0).top(0).height(.navi_height)
        backButton.leading(0).top(.statusHeight).width(56).height(44)
        titleLabel.leading(56)
        titleLabel.CenterY == backButton.CenterY
        exploreLabel.leading(12).trailing(12).top(.navi_height + 12)
        tableView.leading(0).trailing(0).bottom(0)
        tableView.Top == exploreLabel.Bottom + 12.0.Scale
        empteView.leading(0).trailing(0).top(.navi_height + 150.0.Scale).height(200.0.Scale)
        empteView.titleString = "空空如也哟"
        empteView.isHidden = true
        exploreLabel.isHidden = true
        
        backButton.addTarget(self, action: #selector(clickBackButton), for: .touchUpInside)
    }

    private func loadData(){
        
        var isEmpty = true
        dataSource.removeAll()
        if let picDictionary = UserDefaultsManager.getDict(forKey: .picForumPost) {
            isEmpty = false
            dataSource.append(picDictionary)
        }
        
        if let videoDictionary = UserDefaultsManager.getDict(forKey: .videoForumPost) {
            isEmpty = false
            dataSource.append(videoDictionary)
        }
        
        empteView.isHidden = !isEmpty
        exploreLabel.isHidden = isEmpty
        
        self.tableView.reloadData()
    }
    
    private func showAlertView(type: Int){
        let delView = ClubPushForumDraftDelView()
        delView.delBlock = {
            if type == 1 {
                UserDefaultsManager.removeForKey(forKey: .picForumPost)
            }else{
                UserDefaultsManager.removeForKey(forKey: .videoForumPost)
            }
            self.loadData()
        }
        self.entryAnimate.animation(show: delView)
    }
}


extension ClubDraftViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "ClubForumDraftCell", for: indexPath) as! ClubForumDraftCell
        cell.dictionary = dataSource[indexPath.row]
        cell.delBlock = { type in
            self.showAlertView(type: type)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        var height = 74.0.Scale
        
        if let content = dataSource[indexPath.row]["content"] as? String{
            let contentH = content.calculateTextHeight(font: 12.font_regular!, width: CGFloat.screenWidth - 48.0.Scale)
            if contentH >= 35.0.Scale{
                height += 34.0.Scale
            }else{
                height += contentH
            }
        }else{
            height += 18.0.Scale
        }
        if let assetIdentifiers = dataSource[indexPath.row]["assets"] as? [String], assetIdentifiers.count > 0 {
            height += 32.0.Scale
        }else{
            height += 12.0.Scale
        }
        return height
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let dict = dataSource[indexPath.row]
        
        let pushVC = ClubPushForumViewController()
        pushVC.type = dict["type"] as! Int
        pushVC.communityId = self.communityId
        pushVC.titleTextField.text = dict["title"] as? String ?? ""
        if let subject_id = dict["subject_id"] as? String, subject_id.count > 0 {
            pushVC.subject_id = subject_id.components(separatedBy: ",")
        }else{
            pushVC.subject_id = [String]()
        }
        if let gid = dict["gid"] as? String, gid.count > 0 {
            pushVC.gid = gid.components(separatedBy: ",")
        }else{
            pushVC.gid = [String]()
        }
        if let news_id = dict["news_id"] as? String, news_id.count > 0 {
            pushVC.post_id = news_id.components(separatedBy: ",")
        }else{
            pushVC.post_id = [String]()
        }
        if let savedRanges = dict["ranges"] as? [[String: Int]] {
            let ranges = savedRanges.compactMap { dict -> NSRange? in
                if let location = dict["location"], let length = dict["length"] {
                    return NSRange(location: location, length: length)
                }
                return nil
            }
            pushVC.richTextRange = ranges
        }
        if let models = dict["models"] as? Data {
            // 解码为对象数组
            do {
                let decodedItems = try JSONDecoder().decode([ClubTempDynamicGameModel].self, from: models)
                var tempModels = [ClubDynamicGameModel]()
                for mm in decodedItems {
                    let mod = mm.toDynamicGameModel()
                    tempModels.append(mod)
                }
                pushVC.tempArray = tempModels
            }catch{
                print("没有找到存储的数据")
            }
        }

        // 1. 恢复 PHAsset 数组
        var assets: [PHAsset]? = nil
        if let assetIdentifiers = dict["assets"] as? [String] {
            let fetchResult = PHAsset.fetchAssets(withLocalIdentifiers: assetIdentifiers, options: nil)
            assets = fetchResult.objects(at: IndexSet(0..<fetchResult.count))
        }
        pushVC.assets = assets ?? [PHAsset]()
        // 2. 恢复 UIImage 数组
        var images: [UIImage]? = nil
        if let imageDataArray = dict["images"] as? [Data] {
            images = imageDataArray.compactMap { UIImage(data: $0) }
        }
        pushVC.fromDraft = true
        pushVC.images = images ?? [UIImage]()
        pushVC.contentStr = dict["content"] as? String ?? ""
        pushVC.updateDataBlock = {
            self.updateDataBlock?()
            self.navigationController?.popViewController(animated: true)
        }
        
        self.present(pushVC, animated: true)
    }
}
 

class ClubForumDraftCell: UITableViewCell {
    
    private let bgView = c_make_ex(UIView.self)
        .bgColor(.white).corner(8.0.Scale).end()
    private let tagLabel = c_make_ex(UILabel.self)
        .color("#FF7700").font(12.font_medium)
        .text("帖子").end()
    private let timeLabel = c_make_ex(UILabel.self)
        .color("#7D7E80").font(12.font_regular).end()
    private let delButton = c_make_ex(UIButton.self)
        .image("Forum_draft_del").end()
    private let nameLabel = c_make_ex(UILabel.self)
        .color("#323233").font(14.font_semiBold).end()
    private let contentLabel = c_make_ex(UILabel.self)
        .color("#4B4C4D").font(12.font_regular).line(2).end()
    private let mediaLabel = c_make_ex(UILabel.self)
        .color("#4B4C4D").font(12.font_regular).end()

    var dictionary: [String: Any]? {
        didSet{
            guard let dict = dictionary else { return }
            guard let type = dict["type"] as? Int else { return }
            
            if let time = dict["time"] as? String, time.count > 0 {
                timeLabel.text = "上次编辑：" + ClubGlobalTool.shared.timeDescription(from: time, 2)
            }
            if let title = dict["title"] as? String, title.count > 0 {
                nameLabel.text = title
            }else{
                nameLabel.text = "[暂无标题]"
            }
            if let content = dict["content"] as? String, content.count > 0 {
                contentLabel.attributedText = createAttributedText(from: content)
            }else{
                contentLabel.text = "[暂无文字内容]"
            }
            if let images = dict["images"] as? [Data], images.count > 0 {
                if type == 1 {
                    var imgStr = ""
                    for _ in images {
                        imgStr.append("[图片]")
                    }
                    mediaLabel.text = imgStr
                }else{
                    mediaLabel.text = "[视频]"
                }
            }else{
                mediaLabel.text = ""
            }
        }
    }
    
    var delBlock: ((_ type: Int) -> Void)?
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        
        contentView.subviews{
            bgView.subviews{
                tagLabel
                timeLabel
                delButton
                nameLabel
                contentLabel
                mediaLabel
            }
        }
        
        bgView.leading(12.0.Scale).trailing(12.0.Scale).top(0).bottom(12.0.Scale)
        tagLabel.leading(12.0.Scale).top(16.0.Scale)
        timeLabel.leading(44.0.Scale).top(16.0.Scale)
        delButton.trailing(12.0.Scale).top(12.0.Scale).width(42.0.Scale).height(20.0.Scale)
        nameLabel.leading(12.0.Scale).trailing(12.0.Scale).top(44.0.Scale)
        contentLabel.leading(12.0.Scale).trailing(12.0.Scale).top(64.0.Scale)
        mediaLabel.leading(12.0.Scale).trailing(12.0.Scale).height(12.0.Scale)
        mediaLabel.Top == contentLabel.Bottom + 8.0.Scale
        
        delButton.addTarget(self, action: #selector(clickDelButton), for: .touchUpInside)
    }
    
    @objc private func clickDelButton(){  
        
        guard let type = dictionary?["type"] as? Int else { return }
        delBlock?(type)
    }
    
    func createAttributedText(from text: String) -> NSMutableAttributedString {
        let attributedString = NSMutableAttributedString(string: text)
        attributedString.addAttribute(.foregroundColor, value: "#4B4C4D".toColor, range: NSRange(location: 0, length: attributedString.length))
        attributedString.addAttribute(.font, value: 12.font_regular!, range: NSRange(location: 0, length: attributedString.length))
        
        // 正则匹配 [图片]
        let imageTextRegex = try! NSRegularExpression(pattern: "\\[图片\\]", options: [])
        // 处理 [图片] 匹配
        let nsText = text as NSString
        let imageTextMatches = imageTextRegex.matches(in: text, options: [], range: NSRange(location: 0, length: nsText.length))
        
        let offset = 0 // 用于跟踪字符串的偏移量
        
        for match in imageTextMatches {
            let fullMatchRange = NSRange(location: match.range(at: 0).location + offset, length: match.range(at: 0).length)
            // 替换 [图片] 为图片
            let attachment = NSTextAttachment()
            attachment.image = UIImage(named: "Forum_draft_game") // 替换为你的图片
            attachment.bounds = CGRect(x: 0, y: -5, width: 12, height: 12)
            let imageString = NSAttributedString(attachment: attachment)
            attributedString.replaceCharacters(in: NSRange(location: fullMatchRange.location, length: "[图片]".count), with: imageString)
        }
        return attributedString
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
